import java.util.concurrent.PriorityBlockingQueue;

//创建一个描述任务的类
class  MyTask implements  Comparable<MyTask>{
    //具体的任务要干什么
    private Runnable runnable;
    //任务多久干
    private  long time;
    public MyTask(Runnable runnable, long after) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+after;
    }
    //写一个方法
    public  void run(){
        runnable.run();
    }
    //获取任务时间
    public long getTime() {
        return time;
    }
    //重写com
    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time-o.time);
    }
}
class MyTimer1{
    //组织任务，用阻塞队列
    //用优先队列进行排序
    PriorityBlockingQueue<MyTask> queue= new PriorityBlockingQueue<>();
    private  Object lock=new Object();
    public void schedule(Runnable runnable,long time){
        MyTask task=new MyTask(runnable,time);
        //将任务放进队列中
        queue.put(task);
        //每次将任务放进队列中，都要唤醒一次。
        synchronized (lock){
            lock.notify();
        }
    }
    //构造方法
    public   MyTimer1()  {
        Thread t=new Thread(()->{
            while(true) {
                try {
                    MyTask task = queue.take();
                    long time = System.currentTimeMillis();
                    if (time<task.getTime()) {
                        //时间没有到，将任务又重新塞进去
                        queue.put(task);
                        synchronized (lock) {
                            lock.wait(task.getTime() - time);
                        }
                    }else{
                        //时间到了，执行任务
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.start();
    }
}
public class MyTimer {
    public static void main(String[] args) {
        MyTimer1 timer1=new MyTimer1();
        timer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        },3000);
        System.out.println("main");
    }
}
